/*
#------------------------------------------------------------------------------
#-- Program Name:	[dbo].[fnIO_DirectoryName]
#-- Purpose:		Determines the name of a directory given the full path;
#--                 if the directory itself doesn't exists gives a best guess
#--	Last Update:	08/02/2012
#--					For a complete history - please review comments in Version
#--					Control.
#------------------------------------------------------------------------------
*/

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString fnIO_DirectoryName(string filePath)
    {
        if (fnIO_FileExists(filePath))
            return new System.IO.FileInfo(filePath).DirectoryName.ToString();
        else if (fnIO_DirectoryExists(filePath))
        {
            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(filePath);

            if (di.Parent != null)
                return new System.IO.DirectoryInfo(filePath).Parent.FullName;
            else
                return new System.IO.DirectoryInfo(filePath).FullName;
        }
        else
        {
            // Since the file doesn't actually exist, we'll do a best guess
            string[] parts = filePath.Split(System.IO.Path.DirectorySeparatorChar);
            string dirName = "";

            for (int i = 0; i < (parts.Length - 1); i++)
            {
                if (!dirName.Length.Equals(0))
                {
                    if (dirName.Substring(dirName.Length - 1, 1).Equals(":"))
                    {
                        dirName += System.IO.Path.DirectorySeparatorChar;
                    }
                }
                dirName = System.IO.Path.Combine(dirName, parts[i]);
            }

            return dirName;
        }
    }
}
